var PIC = function(adsServer, params){
	this.currentIndex = 0;
	this.serial = [];
	this.loadingImg = "chrome-extension://oifhabgpeonkikolcbijagpodefbkbpj/pic/img/loading1.gif";
	this.defaultCssUrl = "pic.css";
	this.adsServer = adsServer;
	this.defaultWidth = 500;
	this.defaultHeight = 500;
	var storedParams = this.getParams();
	if(storedParams) params = storedParams;
	if(params){
		this.timeout = params.timeout;
		this.width = params.width;
		this.height = params.height;
	}else{
		this.timeout = 1000;
		this.width = 500;
		this.height = 500;
	}
	this.build();
}
PIC.prototype.getParams = function(){
	var params = {};
	params.timeout = localStorage.getItem("pic-stored-timeout");
	params.width = localStorage.getItem("pic-stored-width");
	params.height = localStorage.getItem("pic-stored-height");
	return params;
}
PIC.prototype.build = function(){
	var list = "";
	var listSmall = "";

	var html =  '<div id="pic_wrapper" style="display:none;" class="pic-wrapper" unselectable="on" style="-moz-user-select:none;-webkit-user-select:none;" onselectstart="return false;">'+
					'<a class="pic-close"></a>'+
					'<div class="pic-container">'+
						'<span class="pic-page-count"></span>'+
						'<h2><a></a></h2>'+
						'<div class="pic-viewport">'+
							'<ul id="pic_picture_list">'+
							'</ul>'+
						'</div>'+
						'<div class="pic-prev-mask"></div>'+
						'<div class="pic-next-mask"></div>'+
					'</div>'+
					'<div class="pic-control-panel">'+
						'<a class="pic-prev" href="javascript:void(0)" title="previous"></a>'+
						'<div class="pic-small-list">'+
							'<ul id="pic_picture_list_small">'+
							'</ul>'+
						'</div>'+
						'<a class="pic-next" href="javascript:void(0)" title="next"></a>'+
						'<div class="pic-right">'+
							'<a class="pic-save pic-btn" href="javascript:void(0)" style="display:none"></a>'+
							'<span class="pic-play-ctrl">'+
								'<span class="pic-play-time" href="javascript:void(0)"></span>'+
								'<a class="pic-play pic-btn" href="javascript:void(0)"></a>'+
							'</span>'+
							'<a class="pic-fullscreen pic-btn" href="javascript:void(0)"></a>'+
						'</div>'+
						'<a class="pic-seriallist pic-position-absolut" href="javascript:void(0)"></a>'+
						'<div id="pic_serial_list">'+
							'<ul></ul>'+
						'</div>'+
					'</div>'+
				'</div>';
	// if(!document.querySelector("#pic_wrapper"))
	document.body.insertAdjacentHTML("beforeEnd",html);

	var _this = this;

	this.picWrapper = picWrapper = document.querySelector("#pic_wrapper");


	this.checkbox.init(this.picWrapper.querySelector(".pic-play-time"), function(curValue){
		_this.pause();
		speed = parseInt(curValue)*1000;
		_this.play(speed);
	});

	this.addCss(this.defaultCssUrl);
	picWrapper.querySelector(".pic-next").addEventListener("click",function(){_this.next()});
	picWrapper.querySelector(".pic-prev").addEventListener("click",function(){_this.prev()});
	// this.setTitle(this.title);
	this.viewport = picWrapper.querySelector(".pic-viewport");
	this.list = picWrapper.querySelector("#pic_picture_list li");
	this.setSize(this.width, this.height);


	this.picWrapper.querySelector("#pic_picture_list_small").addEventListener("click", function(event){
		var ele = event.target;
		if(ele.tagName == "IMG"){
			_this.changeTo(util.inArray(ele, _this.picWrapper.querySelectorAll("#pic_picture_list_small img")));
		}
	})

	this.picWrapper.querySelector(".pic-seriallist").addEventListener("click", function(){
		_this.showSerialList();
	})
	this.picWrapper.querySelector("#pic_serial_list ul").addEventListener("click", function(event){
		var target = event.target;
		var li = target.parentNode;
		index = parseInt(li.getAttribute("serial-index"));
		_this.showSerial(_this.serial[index]);
	})
	this.picWrapper.addEventListener('webkitfullscreenchange', function(e) {
	    if (!document.webkitIsFullScreen) {
	       _this.outFullscreen();
	    }
	}, true);
	this.picWrapper.querySelector(".pic-fullscreen").addEventListener("click", function(){
		if(_this.picWrapper.className.match("fullscreen-wrapper")){
			_this.outFullscreen();
		}else{
			_this.fullscreen();
		}
	});
	this.picWrapper.querySelector(".pic-play").addEventListener("click", function(){
		var playBtn = _this.picWrapper.querySelector(".pic-play");
		if(playBtn.className.indexOf("pic-pause")>0){
			_this.pause();
		}else{
			var speed = parseInt(_this.picWrapper.querySelector(".pic-play-time .cur-value").textContent)*1000;
			_this.play(speed);
		}
	});

	this.picWrapper.querySelector(".pic-close").addEventListener("click", function(){
		_this.close();
	})
	var pic_serial_list_hover_timeout;
	var pic_serial_list = this.picWrapper.querySelector("#pic_serial_list");
	pic_serial_list.addEventListener("mouseout", function(event){
		pic_serial_list_hover_timeout = setTimeout(function(){
			pic_serial_list.style.width = "0px";
		},700)
	});
	pic_serial_list.addEventListener("mouseover", function(){
		clearTimeout(pic_serial_list_hover_timeout);
	})

	this.picWrapper.querySelector(".pic-prev-mask").addEventListener("click", function(){_this.prev()});
	this.picWrapper.querySelector(".pic-next-mask").addEventListener("click", function(){_this.next()});
	// window.addEventListener("resize", function(){
	// 	setTimeout(function(){
	// 		_this.setSize();
	// 	},50)
	// })
}
PIC.prototype.checkbox = {
	curIndex:0,
	curValue:"",
	itemClass:"checkbox-item",
	wrapper:null,
	init: function(parentNode, callback){
		this.callback = callback;
		var html = '<div class="custom-checkbox">'+
						'<span class="cur-value">3s</span>'+
						'<ul>'+
							'<li>2s</li>'+
							'<li>3s</li>'+
							'<li>5s</li>'+
						'</ul>'+
					'</div>';
		parentNode.innerHTML = html;
		this.wrapper = parentNode.querySelector(".custom-checkbox");
		this.bindEvents();
	},
	addItem: function(){

	},
	select: function(item){
		this.curIndex = util.inArray();
		this.curValue = item.innerText;
		this.wrapper.querySelector(".cur-value").textContent = this.curValue;
		this.callback(this.curValue);
	},
	selectByIndex: function(index){
		this.curIndex = index;
		this.curValue = this.wrapper.querySelectorAll("li")[index].innerText;
		this.wrapper.querySelector(".cur-value").textContent = this.curValue;
		this.callback(this.curValue);
	},
	bindEvents: function(){
		var _this = this;
		var timeout;
		this.wrapper.addEventListener("mouseover", function(){
			clearTimeout(timeout);
			_this.wrapper.querySelector("ul").style.display = "block";
		});
		this.wrapper.addEventListener("mouseout", function(){
			timeout = setTimeout(function(){
				_this.wrapper.querySelector("ul").style.display = "none";
			},500)
		});
		this.wrapper.querySelector("ul").addEventListener("click", function(event){
			if(event.target.tagName === "LI"){
				_this.select(event.target);
			}
		})
	}
}
PIC.prototype.show = function(option){
	this.picWrapper.style.display = "block";
	if(this.serial[0]) this.showSerial(this.serial[0]);
	if(option == "fullscreen"){
		this.fullscreen();
		this.outFullscreenOption = "close";	
	}
}
PIC.prototype.close = function(){
	this.picWrapper.style.display = "none";
	this.pause();
}

PIC.prototype.play = function(speed){
	if(!speed)speed =3000;
	var playBtn = this.picWrapper.querySelector(".pic-play");
	playBtn.className = playBtn.className+ " pic-pause";
	var _this = this;
	this.playInterval = setInterval(function(){
		if(_this.currentIndex == _this.length - 1){
			_this.changeTo(0);
		}else{
			_this.next();
		}
	}, speed);
	this.picWrapper.querySelector(".pic-play-time").style.display = "inline-block";
}
PIC.prototype.pause = function(){
	var playBtn = this.picWrapper.querySelector(".pic-play");
	playBtn.className = playBtn.className.replace(/ *pic-pause/, "");
	clearInterval(this.playInterval);
	this.picWrapper.querySelector(".pic-play-time").style.display = "none";
}
PIC.prototype.fullscreen = function(){
    var el = this.picWrapper
        , rfs =
               el.requestFullScreen
            || el.webkitRequestFullScreen
            || el.mozRequestFullScreen
    ;
    rfs.call(el);
    // this.picWrapper.style.height = screen.height;
    this.picWrapper.className+=" fullscreen-wrapper";
    this.setSize(screen.width, screen.height, true);
}
PIC.prototype.outFullscreen = function(){
	if(document.webkitIsFullScreen){
	    var el = document
	        , rfs =
	               el.exitFullscreen
	            || el.webkitCancelFullScreen
	            || el.mozCancelFullScreen
	    ;
	    rfs.call(el);
	}
	var width = parseInt(localStorage.getItem("pic-stored-width"));
	width = width?width:this.defaultWidth;
	var height = parseInt(localStorage.getItem("pic-stored-height"));
	height = height?height:this.defaultHeight;
	this.picWrapper.className = this.picWrapper.className.replace(/ *fullscreen-wrapper/, "");
	if(this.outFullscreenOption == "close"){
		this.close();
	}else{
		this.setSize(width,height);
	}
    // this.picWrapper.style.height = "auto";
}
PIC.prototype.addSerial = function(title, imgUrls){
	var i = 0;
	for(; i < this.serial.length; i++){
		if(this.serial[i].title == title) break;
	}
	if(i == this.serial.length){
		this.serial.push({title:title, imgUrls:imgUrls});
		var serialList = this.picWrapper.querySelector("#pic_serial_list ul");
		var html =  '<li serial-index="'+(this.serial.length-1)+'">'+
						'<img src="'+imgUrls[0]+'"></img><a href="javascript:void(0)">'+title+'</a>'+
					'</li>';
		serialList.insertAdjacentHTML("beforeEnd",html);
	}
}
PIC.prototype.showSerial = function(serial){
	if(typeof serial == "string"){
		serial = this.getSerialByTitle(serial);
	}
	var title = serial.title;
	var imgUrls = serial.imgUrls;
	var list = '';
	this.currentIndex = 0;
	for(var len = imgUrls.length, i = 0; i < len; i++){
		list+='<li liIndex="'+i+'"><img class="pic-delayed-img" src="'+ this.loadingImg +'" data-original="'+imgUrls[i]+'"></li>';
	}
	var pictureList = this.picWrapper.querySelector("#pic_picture_list");
	pictureList.innerHTML = '<a class="pic-vertical-ele"></a>'+list;

	var smallPictureList = this.picWrapper.querySelector("#pic_picture_list_small");
	smallPictureList.innerHTML = list;
	this.smallList = this.picWrapper.querySelectorAll("#pic_picture_list_small li");

	var tmpVar = this.picWrapper.querySelector("#pic_serial_list li.pic-li-actived");
	tmpVar && (tmpVar.className = tmpVar.className.replace(/ *pic-li-actived/, ""));

	tmpVar = this.picWrapper.querySelectorAll("#pic_serial_list li a");
	for(var i = 0; i < tmpVar.length; i++){
		if(tmpVar[i].textContent == title){
			tmpVar[i].parentNode.className += "pic-li-actived";
			break;
		}
	}

	var imgEles = pictureList.querySelectorAll(".pic-delayed-img");
	var _this = this;
	for(var len = imgEles.length, i = 0; i < len; i++){
		this.loadImage(imgEles[i], function(index){
			return function(){
				var img = _this.smallList[index].querySelector("img");
				img.setAttribute("src", img.getAttribute("data-original"));
			}
		}(i));
	}
	// smallPictureList.querySelector("li").className+=" actived";
	this.adjustBigList();
	this.adjustSmallList();

	var pc = this.picWrapper.querySelector(".pic-page-count");
	pc.innerText = '[1/'+imgUrls.length+']';

	this.length = this.smallList.length;
	this.changeTo(0);

	this.picWrapper.style.display = "block";


}
PIC.prototype.getSerialByTitle = function(title){
	var s = null;
	for(var i = 0; i < this.serial.length; i++){
		if(this.serial[i].title == title){
			s = this.serial[i];
			break;
		}
	}
	return s;
}
PIC.prototype.showSerialList = function(){
	var serialList = this.picWrapper.querySelector("#pic_serial_list");
	var width = parseInt(serialList.style.width);
	width = width? width:0;
	function swing( p ) {
		return 0.5 - Math.cos( p*Math.PI ) / 2;
	}
	var times = 0;
	if(!width || width == 0){
		// var interval = setInterval(function(){
		// 	serialList.style.width=(width=swing(times++/150)*300);
		// 	if(times == 150) clearInterval(interval);
		// }, 1)
		serialList.style.width = "300px";
	}else{
		// var interval = setInterval(function(){
		// 	serialList.style.width=(300-swing(times++/150)*300);
		// 	if(times == 150) clearInterval(interval);
		// }, 1)
		serialList.style.width = "0px";
	}
	var timeout = setTimeout(function(){
		serialList.style.width = "0px";
	}, 3000);
	serialList.addEventListener("mouseover", function mouseover(){
		clearTimeout(timeout);
		serialList.removeEventListener(mouseover);
	})
}
PIC.prototype.closeSerialList = function(){
	var serialList = this.picWrapper.querySelector("#pic_serial_list");
	var interval = setInterval(function(){
		serialList.style.width-=1;
		if(serialList.style.width == 0) clearInterval(interval);
	}, 1)
}
PIC.prototype.setTitle = function(title){
	this.picWrapper.querySelector("h2 a").innerText = title;
}
PIC.prototype.changeTo = function(index){
	this.viewport.scrollLeft = this.width*index;
	focusedLi = this.smallList[this.currentIndex]
	focusedLi.className = focusedLi.className.replace(" actived", "");
	this.smallList[index].className+=" actived";
	var list = this.picWrapper.querySelector(".pic-small-list");

	if((index >= this.visibleCount && index> this.currentIndex)|| (index < list.scrollLeft/this.smallWidth && index < this.currentIndex)){
		var scrollLeft=this.smallWidth*(index+1-this.visibleCount);
		list.scrollLeft = scrollLeft;
	}
	this.currentIndex = index;

	var pc = this.picWrapper.querySelector(".pic-page-count");
	pc.innerText = '['+(index+1)+'/'+this.length+']';
}
PIC.prototype.next = function(){
	if(this.currentIndex == this.length - 1) return;
	this.changeTo(this.currentIndex+1);
}
PIC.prototype.prev = function(){
	if(this.currentIndex == 0) return;
	this.changeTo(this.currentIndex-1);
}
PIC.prototype.setSize = function(width, height, notSaveLocalStorage){
	if(!width) {
		width = localStorage.getItem("pic-stored-width");
		// width = width>window.innerWidth?window.innerWidth:width;
	}
	if(!height){
		height =localStorage.getItem("pic-stored-height");
		// height = height>window.innerHeight?window.innerHeight:height;
	}
	this.width = width;
	this.height = height;
	var viewport = this.picWrapper.querySelector(".pic-viewport");
	viewport.style.width = width+"px";
	viewport.style.height = height+"px";

	var serialList = this.picWrapper.querySelector("#pic_serial_list");
	serialList.style.maxHeight = height+"px";
	// this.picWrapper.querySelector(".pic-control-panel").style.width = width+"px";
	this.picWrapper.style.width = width+"px";
	this.viewport.scrollLeft = this.width*this.currentIndex;

	this.adjustBigList();
	this.adjustSmallList();
	if(!notSaveLocalStorage){
		localStorage.setItem("pic-stored-width", this.width);
		localStorage.setItem("pic-stored-height", this.height);
	}

	var adsEles = this.picWrapper.querySelectorAll(".pic-ad-picture");
	for(var i = 0; i < adsEles.length; i++){
		this.adjustAdsPicture(adsEles[i]);
	}
}
PIC.prototype.adjustBigList = function(){

	var viewport = this.viewport;
	var width = this.width;
	var height = this.height;
	var liEles = viewport.querySelectorAll("li");
	for(var i = 0, len = liEles.length;i < len; i++){
		liEles[i].style.width = width+"px";
	}

	var imgEles = viewport.querySelectorAll("img");
	for(var i = 0, len = imgEles.length;i < len; i++){
		this.setImgSize(imgEles[i]);
	}
	var verticalEle = viewport.querySelector(".pic-vertical-ele")
	verticalEle && (verticalEle.style.height = this.height+"px");

}
PIC.prototype.adjustSmallList = function(){
	var ctrlPanel = this.picWrapper.querySelector(".pic-control-panel");
	var list = this.picWrapper.querySelector(".pic-small-list");
	var len = list.querySelectorAll("li").length;
	// var width = this.smallWidth;
	var width = this.width;
	var smallWidth = 32+6;
	var className = "size32";
	if(width>800){
		smallWidth = 48+6;
		className = "size48";
	}
	if(ctrlPanel.className && ctrlPanel.className.match(/size\d+/)){
		ctrlPanel.className = ctrlPanel.className.replace(/size\d+/, className);
	}else{
		ctrlPanel.className+=(" "+className);
	}
	var count = parseInt(width/2/smallWidth);
	count = count>len?len:count;
	list.style.width = smallWidth*count+"px";

	list.scrollLeft=this.currentIndex+1-count;
	if(this.currentIndex>=count){
		list.scrollLeft = (this.currentIndex+1-count)*smallWidth;
	}else{
		list.scrollLeft = 0;
	}

	this.visibleCount = count;
	this.smallWidth = smallWidth;
}
PIC.prototype.addCss = function(cssUrl){
	if(!cssUrl) cssUrl = this.defaultCssUrl;
	// var ele = document.createElement("link");
	// ele.setAttribute("rel", "stylesheet");
	// ele.href = cssUrl;
	// document.head.appendChild(ele);
	adapter.insertCSS("pic/pic.css");
}
PIC.prototype.setImgSize = function(imgEle){
	var width = this.width;
	var height = this.height;
	var oriWidth = imgEle.getAttribute("oriWidth");
	var oriHeight = imgEle.getAttribute("oriHeight");
	if(!oriWidth || !oriHeight) return;
	var rate = (width/oriWidth < height/oriHeight)?width/oriWidth:height/oriHeight;
	var rtn;
	if(rate <= 1){
		rtn= {width:oriWidth*rate,height:oriHeight*rate};
	}else {
		rtn= {width:oriWidth,height:oriHeight};
	}
	imgEle.style.width = rtn.width+"px";
	imgEle.style.height = rtn.height+"px";
}
PIC.prototype.loadImage = function(imgEle, callback){
    var _this=this;
	var originalUrl = imgEle.getAttribute("data-original");
	var browser={}; 
    browser.userAgent=window.navigator.userAgent.toLowerCase();
    browser.ie=/msie/.test(browser.userAgent); 
    browser.Moz=/gecko|opera/i.test(browser.userAgent);
    var img=new Image();
    if(browser.ie){
        img.onreadystatechange =function(){
			if(img.width>0 && img.height>0){
	            if(img.readyState=="complete"||img.readyState=="loaded"){
	                setTimeout(function(){
	                	imgEle.setAttribute("oriWidth", img.width);
	                	imgEle.setAttribute("oriHeight", img.height);
	                	_this.setImgSize(imgEle);
	                	imgEle.src = originalUrl;
	                	callback();
	                }, 13);
	            }
	        }
        }
    }else if(browser.Moz){
        img.onload=function(){
            if(img.complete==true){
            	imgEle.setAttribute("oriWidth", img.width);
            	imgEle.setAttribute("oriHeight", img.height);
            	_this.setImgSize(imgEle);
                imgEle.src = originalUrl;
                callback();
            }
        }
    }
    var _this = this;
    img.onerror=function(){
    	// imgEle.style.display = "none";
    	// _this.insertAdPicture(imgEle.parentNode);
    	// pic.getAdsPicture(function(imgUrl){
	    // 	img.src = imgUrl;
	    // 	originalUrl = imgUrl;
    	// });
        // obj.src = error.img;
        // obj.width = error.w;
        // obj.height = error.h;
        // obj.setAttribute("data-original",error.img);
        // S.model.status.loadedImg[url]=false;
    }
    img.src=originalUrl;
}
PIC.prototype.insertAdPicture = function(ele){
	var ad = this.getAdsPicture("img");
	var html = '<div class="pic-ad-picture">'+
					'<a class="pic-ad-vertical-ele"/>'+
					'<a class="pic-ad-a" target="_blank" href="'+ad.targetUrl+'">'+
						'<img src="'+this.loadingImg+'" data-original="'+ad.url+'"/>'+
					'</a>'+
					'<a class="pic-ads-buy" target="_blank" href="'+ad.targetUrl+'">购买</a>'+
					'<span class="pic-ads-mark">广告图片<span>'+
			   '</div>'
	if(ele){
		ele.insertAdjacentHTML("beforeEnd", html);
	}else{

	}
	this.adjustAdsPicture(ele.querySelector(".pic-ad-picture"));
	var imgEle = ele.querySelector(".pic-ad-picture img");
	this.loadImage(imgEle, function(){
		var i = parseInt(ele.getAttribute("liIndex"));
		this.picWrapper.querySelectorAll("#pic_picture_list_small li img")[i].src = ad.url;
	})
}
PIC.prototype.adjustAdsPicture =function(adEle){
	var ve = adEle.querySelector(".pic-ad-vertical-ele");
	ve.style.height = this.height+"px";
	var ada = adEle.querySelector(".pic-ad-a");
	ada.style.width = this.width+"px";
	adEle.style.width = this.width+"px";
	adEle.style.height = this.height+"px";
}
PIC.prototype.getAdsPicture = function(type){
	var ad;
	if(type == "img"){
		ad = {
			title:"nike男鞋",
			url:"http://img02.taobaocdn.com/imgextra/i2/1824506246/TB2rQLfXVXXXXb.XXXXXXXXXXXX_!!1824506246.jpg_.webp",
			targetUrl:"http://detail.tmall.com/item.htm?spm=a230r.1.14.1.DJ7xpG&id=36553385503&ad_id=&am_id=&cm_id=140105335569ed55e27b&pm_id="
		}
	}else if(type == "iframe"){
		ad = {
			title:"nike男鞋",
			url:"http://img02.taobaocdn.com/imgextra/i2/1824506246/TB2rQLfXVXXXXb.XXXXXXXXXXXX_!!1824506246.jpg_.webp",
			width:"300px",
			height:"250px"
		}
	}
	return ad;
}

